import 'package:file_picker/file_picker.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
import 'package:path/path.dart' as path;
import 'package:permission_handler/permission_handler.dart';
import 'package:wechat_assets_picker/wechat_assets_picker.dart';

import '../../config/public_text.dart';
import '../../model/key_value_model.dart';
import '../../tool/permission_manager.dart';
import '../dialog/public_alert_dialog.dart';
import 'action_sheet.dart';

/// FileName upload_file_action_sheet
///
/// @Author lax
/// @Date 2023/3/6
///
/// @Description 图片选择器

enum UploadFileAction {
  selectPhoto, // 相册
  takePhoto, // 拍照
  selectVideo, // 选择视频
  captureVideo, // 拍摄视频
  selectFile, // 文件
}

class UploadFileActionSheet {
  static show<T>({
    required BuildContext context,
    List<UploadFileAction> actions = const [
      UploadFileAction.selectPhoto,
      UploadFileAction.takePhoto,
      UploadFileAction.selectVideo,
      UploadFileAction.captureVideo,
    ],
    Function(List<String> paths)? onSelected, // 选择图片
    Function(List<Uint8List> datas)? onSelectedDatas,
    int maxCount = 1,
    Function(int maxCount)? onUpperBound, // 超过数量上限
    List? allowedExtensions, // 文件格式限制
    Function(String extension)? onUnsupportedExtension, // 不支持的文件格式
  }) {
    final picker = ImagePicker();
    final dataSource = actions
        .map((e) => KeyValueModel(
            id: e.index,
            value: {
              UploadFileAction.selectPhoto: PublicText.album,
              UploadFileAction.takePhoto: PublicText.takePhoto,
              UploadFileAction.selectVideo: PublicText.selectVideo,
              UploadFileAction.captureVideo: PublicText.captureVideo,
              UploadFileAction.selectFile: PublicText.selectFile,
            }[e]))
        .toList();
    ActionSheet.show(
      context: context,
      dataSource: dataSource,
      onSelected: (value) async {
        if (value.id == 0) {
          // 请求权限
          final pass = await PermissionManager.requestPermission(
            permissionList: [
              Permission.storage,
              Permission.photos,
            ],
          );
          if (!pass) {
            if (!context.mounted) {
              return;
            }
            PublicAlertDialog.show(
                context: context,
                title: await PermissionManager.isAndroidAPIBelow33()
                    ? PublicText.noStoragePermission
                    : PublicText.noPhotosVideoPermission,
                message: PublicText.pleaseOpenPermission,
                confirmText: PublicText.toSetting,
                onConfirm: () {
                  openAppSettings();
                });
            return;
          }

          if (kIsWeb) {
            final image = await picker.pickImage(source: ImageSource.gallery);
            if (image != null) {
              onSelected?.call([image.path]);
            }
            if (onSelectedDatas != null) {
              image?.readAsBytes().then((value) {
                onSelectedDatas.call([value]);
              });
            }
            return;
          }

          // 调用相册
          if (!context.mounted) {
            return;
          }
          final pickedAssets = await AssetPicker.pickAssets(context,
              pickerConfig: AssetPickerConfig(
                  requestType: RequestType.image, maxAssets: maxCount));

          if (pickedAssets != null) {
            final List<String> filePaths = [];
            for (var asset in pickedAssets) {
              final originFile = await asset.originFile;
              final filePath = originFile?.path;
              if (filePath != null && asset.type == AssetType.image) {
                filePaths.add(filePath);
              }
            }
            onSelected?.call(filePaths);
          }
        } else if (value.id == 1) {
          // 请求权限
          final pass = await PermissionManager.requestPermission(
            permissionList: [
              Permission.camera,
            ],
          );
          if (!pass) {
            if (!context.mounted) {
              return;
            }
            PublicAlertDialog.show(
                context: context,
                title: PublicText.noCameraPermission,
                message: PublicText.pleaseOpenPermission,
                confirmText: PublicText.toSetting,
                onConfirm: () {
                  openAppSettings();
                });
            return;
          }

          // 拍摄照片
          final image = await picker.pickImage(source: ImageSource.camera);
          if (image != null) {
            onSelected?.call([image.path]);
          }
        } else if (value.id == 2) {
          // 请求权限
          final pass = await PermissionManager.requestPermission(
            permissionList: [
              Permission.storage,
              Permission.photos,
            ],
          );
          if (!pass) {
            if (!context.mounted) {
              return;
            }
            PublicAlertDialog.show(
                context: context,
                title: await PermissionManager.isAndroidAPIBelow33()
                    ? PublicText.noStoragePermission
                    : PublicText.noPhotosVideoPermission,
                message: PublicText.pleaseOpenPermission,
                confirmText: PublicText.toSetting,
                onConfirm: () {
                  openAppSettings();
                });
            return;
          }

          if (kIsWeb) {
            final image = await picker.pickVideo(source: ImageSource.gallery);
            if (image != null) {
              onSelected?.call([image.path]);
            }
            if (onSelectedDatas != null) {
              image?.readAsBytes().then((value) {
                onSelectedDatas.call([value]);
              });
            }
            return;
          }

          // 选择视频
          if (!context.mounted) {
            return;
          }
          final pickedAssets = await AssetPicker.pickAssets(context,
              pickerConfig: AssetPickerConfig(
                  requestType: RequestType.video, maxAssets: maxCount));

          if (pickedAssets != null) {
            final List<String> filePaths = [];
            for (var asset in pickedAssets) {
              final originFile = await asset.originFile;
              final filePath = originFile?.path;
              if (filePath != null && asset.type == AssetType.video) {
                filePaths.add(filePath);
              }
            }
            onSelected?.call(filePaths);
          }
        } else if (value.id == 3) {
          // 请求权限
          var pass = await PermissionManager.requestPermission(
            permissionList: [
              Permission.camera,
            ],
          );
          if (!pass) {
            if (!context.mounted) {
              return;
            }
            PublicAlertDialog.show(
                context: context,
                title: PublicText.noCameraPermission,
                message: PublicText.pleaseOpenPermission,
                confirmText: PublicText.toSetting,
                onConfirm: () {
                  openAppSettings();
                });
            return;
          }
          pass = await PermissionManager.requestPermission(
            permissionList: [
              Permission.microphone,
            ],
          );
          if (!pass) {
            if (!context.mounted) {
              return;
            }
            PublicAlertDialog.show(
                context: context,
                title: PublicText.noMicrophonePermission,
                message: PublicText.pleaseOpenPermission,
                confirmText: PublicText.toSetting,
                onConfirm: () {
                  openAppSettings();
                });
            return;
          }

          // 拍摄视频
          final image = await picker.pickVideo(source: ImageSource.camera);
          if (image != null) {
            onSelected?.call([image.path]);
          }
        } else if (value.id == 4) {
          // 请求权限
          // final pass = await PermissionManager.requestPermission(
          //   permissionList: [
          //     Permission.storage,
          //     Permission.photos,
          //     Permission.videos,
          //   ],
          // );
          // if (!pass) {
          //   if (!context.mounted) {
          //     return;
          //   }
          //   PublicAlertDialog.show(
          //       context: context,
          //       title: await PermissionManager.isAndroidAPI33()
          //           ? PublicText.noPhotosVideoPermission
          //           : PublicText.noStoragePermission,
          //       message: PublicText.pleaseOpenPermission,
          //       confirmText: PublicText.toSetting,
          //       onConfirm: () {
          //         openAppSettings();
          //       });
          //   return;
          // }

          // 选择文件
          FilePickerResult? result = await FilePicker.platform.pickFiles();
          final files = (result?.files ?? [])
              .where((element) => element.path != null)
              .toList();
          final paths = files.map((e) => e.path ?? '').toList();
          List<String> unsupportedExtensions = [];
          if (allowedExtensions != null) {
            final extensions =
                files.map((e) => path.extension(e.name)).toList();
            unsupportedExtensions = extensions
                .where((e) => !allowedExtensions.contains(e))
                .toList();
          }
          if (paths.length > maxCount) {
            onUpperBound?.call(maxCount);
          } else if (paths.isNotEmpty) {
            if (unsupportedExtensions.isNotEmpty) {
              onUnsupportedExtension?.call(unsupportedExtensions.join(', '));
            } else {
              onSelected?.call(paths);
            }
          }
        }
      },
    );
  }
}
